package com.example.application2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ShrdpreActivity extends AppCompatActivity {

    private final static String SharedPreferencesFileName = "config";

    private final static String Key_UserName = "StudentIDAndName";
    private final static String Key_LoginDate = "LoginDate";
    private final static String Key_UserType = "UserType";

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    private Button btn_write;
    private Button btn_read;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shrdpre);

        preferences = getSharedPreferences(SharedPreferencesFileName, MODE_PRIVATE);
        editor = preferences.edit();

        btn_write = findViewById(R.id.btn_write);
        btn_read = findViewById(R.id.btn_read);
        btn_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String strLoginDate = simpleDateFormat.format(new Date());

                editor.putString(Key_UserName, "2016011427陈希星");
                editor.putString(Key_LoginDate, strLoginDate);
                editor.putInt(Key_UserType, 1);
                editor.apply();
            }
        });

        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strUserName = preferences.getString(Key_UserName, null);
                String strLoginDate = preferences.getString(Key_LoginDate, null);
                int nUserType = preferences.getInt(Key_UserType, 0);
                if (strUserName != null && strLoginDate != null){
                    Toast.makeText(ShrdpreActivity.this, "用户名：" + strUserName + "登录时间：" + strLoginDate + "用户类型：" + nUserType, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(ShrdpreActivity.this, "无数据", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}